<?php

namespace common\services;

use yii\web\UploadedFile;

class UploadLocalServices
{
    public static function uploadLocalFu($name = 'file', $sizeConfig = ['xlsx' => 10, 'png' => 1], $isEncode = false): array
    {
        try {
            //按名称获取实例
            $file = UploadedFile::getInstanceByName($name);

            if (empty($file)) {
                return ['code' => 1, 'msg' => '上传失败，没有文件！'];
            }
            //是否有错误
            if ($file->getHasError()) {
                return ['code' => 1, 'msg' => '文件异常！'];
            }

            //1M
            $default = 1048576;
            //匹配文件后缀
            $extension = $file->getExtension();
            if (!in_array($extension, array_keys($sizeConfig))) {
                return ['code' => 1, 'msg' => '暂不支持上传' . $extension . '文件'];
            }
            if ($file->size > $sizeConfig[$extension] * $default) {
                return ['code' => 1, 'msg' => '上传文件过大！'];
            }

            $basePath = 'uploads/';

            //文件名
            $fileName = date('His') . md5(uniqid()) . '.' . $extension;
            //路径
            $savePath = $basePath  . $fileName;
            if ($file->saveAs($savePath)) {
                if (!file_exists($savePath)) {
                    return ['code' => 1, 'msg' => '文件保存失败！'];
                }

                $path = $savePath;
                return ['code' => 0, 'msg' => '上传成功！', 'data' => [
                    'fileName' => $fileName,
                    'path' => $isEncode ? base64_encode($path) : $path,
                    'extension' => $extension,
                    'size' => $file->size . 'Byte'
                ]];
            }
            return ['code' => 1, 'msg' => '文件保存异常！'];
        } catch (\Exception $e) {
            return ['code' => 1, 'msg' => '调用失败'.$e->getMessage()];
        }
    }

}